package com.smartens.boit.util

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.*
import android.util.Log
import android.view.*
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.smartens.boit.databinding.DialogBrightnessPlanBinding
import com.smartens.boit.util.PickerScrollView.onSelectListener
import java.io.Serializable

private const val ARG_PARAM1 = "pickerList"
private const val TAG = "CustomBrightnessPlanDia"

class CustomBrightnessPlanDialog : DialogFragment() {
    private var rootView: View? = null
    private var mDecorView: View? = null
    private var mIntoSlide: Animation? = null
    private var mOutSlide: Animation? = null
    var dialogCallback: DialogCallback? = null
    private var isClick = false
    private val mInputHandler: InputHandler = InputHandler()
    private var firstSelected: String? = null
    private var flags = false
    private val firstTime: Long = 0

    private var cancel: TextView? = null
    private var save: TextView? = null
    lateinit var binding: DialogBrightnessPlanBinding
    lateinit var pslBrightness: PickerScrollView


    /**
     * 通讯回调接口
     */
    interface DialogCallback {
        fun confirm(hour: String?)
    }

    companion object {
        @JvmStatic
        fun newInstance(pickers: MutableList<Pickers>): CustomBrightnessPlanDialog =
            CustomBrightnessPlanDialog().apply {
                Bundle().apply {
                    putSerializable(ARG_PARAM1, pickers as Serializable)
                    arguments = this
                }
            }

        @JvmStatic
        fun newInstance(
            pickers: MutableList<Pickers>,
            selected: String
        ): CustomBrightnessPlanDialog =
            CustomBrightnessPlanDialog().apply {
                Bundle().apply {
                    putSerializable(ARG_PARAM1, pickers as Serializable)
                    putString("selected", selected)
                    arguments = this
                }
            }

    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DialogBrightnessPlanBinding.inflate(layoutInflater)
        rootView = binding.root
        pslBrightness = binding.pslBrightnessPlan
        save = binding.save
        cancel = binding.cancel
        initPickerViewData()
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //弹窗弹入屏幕的动画
        initIntAnimation()
        //初始化监听
        initListener()
        //手指点击弹窗外处理
        touchOutShowDialog()
        //back键处理
        focus
    }

    private fun initPickerViewData() {
        getProjectInfo()
    }


    private fun getProjectInfo() {
        initDialogView()
        val list: List<Pickers> = arguments?.getSerializable(ARG_PARAM1) as List<Pickers>
        val selected = arguments?.getString("selected")
        val newList = mutableListOf<Pickers>()
        newList.addAll(list)
        firstSelected = list.filter { it.showConetnt == selected }.let { it[0].showId }
        pslBrightness.setData(newList)
        if (selected != null) {
            pslBrightness.setSelected(selected)
        }
    }

    /**
     * 根据业务需求，更改弹窗的一些样式
     */
    private fun initDialogView() {
        mDecorView = dialog!!.window!!.decorView
        //设置背景为透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mDecorView!!.background = ColorDrawable(Color.TRANSPARENT)
        }
        val window = dialog!!.window
        val layoutParams = window!!.attributes
        //居屏幕底部
        layoutParams.gravity = Gravity.BOTTOM
        //给window宽度设置成填充父窗体，解决窗体宽度过小问题
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT
        window.attributes = layoutParams
        mDecorView!!.setPadding(0, 0, 0, 0)
        window.decorView.minimumWidth = resources.displayMetrics.widthPixels
    }


    private fun initListener() {
        pslBrightness.setOnSelectListener(firstPickerListener)
        save?.setOnClickListener(clickListener)
        cancel?.setOnClickListener(clickListener)
    }

    inner class InputHandler : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                confirmButtonClickable()
            }
        }
    }

    private fun confirmButtonClickable() {
        flags = true
        if (System.currentTimeMillis() - firstTime > 500) {
            flags = false
        } else {
            mInputHandler.sendEmptyMessageDelayed(1, 300)
        }
    }

    /**
     * 弹窗弹入屏幕的动画
     */
    protected fun initIntAnimation() {
        if (mIntoSlide != null) {
            mIntoSlide!!.cancel()
        }
        mIntoSlide = TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 1.0f,
            Animation.RELATIVE_TO_SELF, 0.0f
        )
        mIntoSlide?.duration = 200
        mIntoSlide?.fillAfter = true
        mIntoSlide?.isFillEnabled = true
        view?.startAnimation(mIntoSlide)
    }

    /**
     * 过滤重复点击
     */
    fun dismissDialog() {
        if (isClick) {
            return
        }
        isClick = true
        initOutAnimation()
    }

    /**
     * 弹窗弹出屏幕的动画
     */
    private fun initOutAnimation() {
        if (mOutSlide != null) {
            mOutSlide!!.cancel()
        }
        mOutSlide = TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 1.0f
        )
        mOutSlide?.duration = 200
        mOutSlide?.isFillEnabled = true
        mOutSlide?.fillAfter = true
        view?.startAnimation(mOutSlide)
        /**
         * 弹出屏幕动画的监听
         */
        mOutSlide?.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                //过滤重复点击的标记
                isClick = false
                //销毁弹窗
                dismiss()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }

    /**
     * 拦截手势(弹窗外区域)
     */
    private fun touchOutShowDialog() {
        mDecorView?.setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                //弹框消失的动画执行相关代码
                dismissDialog()
            }
            true
        }
    }//关闭弹窗//判断弹窗是否显示// 监听到back键(悬浮手势)返回按钮点击事件

    /**
     * 监听主界面back键
     * 当点击back键时，执行弹窗动画
     */
    private val focus: Unit
        private get() {
            view?.isFocusableInTouchMode = true
            view?.requestFocus()
            view?.setOnKeyListener(View.OnKeyListener { v, keyCode, event -> // 监听到back键(悬浮手势)返回按钮点击事件
                if (event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    //判断弹窗是否显示
                    if (this@CustomBrightnessPlanDialog.dialog!!.isShowing) {
                        //关闭弹窗
                        dismissDialog()
                        return@OnKeyListener true
                    }
                }
                false
            })
        }

    /**
     * 选择器选中事件
     */
    private val firstPickerListener =
        onSelectListener { pickers -> // Toast.makeText(getContext(),pickers.getShowId(),Toast.LENGTH_SHORT).show();
            firstSelected = pickers.showId

        }

    /**
     * 点击事件
     */
    private val clickListener =
        View.OnClickListener { v ->
            if (v === cancel) {
                dismissDialog()
            } else if (v === save) {
                dialogCallback!!.confirm(firstSelected)
            }
        }
}